package cn.accjiyun.translator.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class SearchYouDaoAPI extends Thread {

	private static String doctype = "xml";
	protected String urlInterface = "http://fanyi.youdao.com/openapi.do?keyfrom=trhdrrth&key=1472033710&type=data&doctype="
			+ doctype + "&version=1.1&q=";
	private String urlYouDao = null;
	private StringBuilder builder = new StringBuilder();

	public static String getDoctype() {
		return doctype;
	}
	
	public StringBuilder getBuilder() {
		return builder;
	}

	public SearchYouDaoAPI(String originalString) {
		try {
			urlYouDao = urlInterface + URLEncoder.encode(originalString,   "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {

			URL url = new URL(urlYouDao);
			URLConnection connection = url.openConnection();
			connection.connect();
			InputStream is = connection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(isr);

			String line;
			while ((line = br.readLine()) != null) {
				builder.append(line);
			}
			br.close();
			isr.close();
			br.close();
			
			WriteStringToFile(builder.toString());

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void WriteStringToFile(String outString) {

		try {
			BufferFolder bufferFolder = new BufferFolder();
			FileOutputStream fos = new FileOutputStream(bufferFolder + "data." + doctype);
			byte output[] = outString.getBytes();
			fos.write(output);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
